package com.ray.friendslist.database.common;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

abstract public class CommonDataBase extends CommonDataBaseHelper {

	private SQLiteDatabase database;

	private InsertOrQuery mInsertOrQuery;

	protected CommonDataBase(Context context, final String tableName,
			final String[] coloumns) {
		super(context, null, tableName, coloumns);
		mInsertOrQuery = null;
		mInsertOrQuery = new InsertOrQuery() {

			public Cursor getItem() {
				// TODO Auto-generated method stub
				database = getReadableDatabase();
				Cursor cursor = database.query(tableName, null, null, null,
						null, null, null);
				return cursor;
			}

			public long addItem(JSONObject jsonObject) throws JSONException {
				database = getWritableDatabase();
				Log.d("ray", "adding item");
				// String where = coloumns[0] + " = ?";
				long value;
				ContentValues values = getContentValues(jsonObject);
				value = database.insertWithOnConflict(tableName, null, values,
						SQLiteDatabase.CONFLICT_REPLACE);
				/*
				 * if (value == -1) { Log.d("ray", "already exist"); return
				 * database.update(tableName, values, where, new String[] {
				 * values.getAsString(coloumns[0]) }); }
				 */
				return value;
			}
		};
	}

	public static void withoutConstructor(Context context,
			final String tableName, final String[] coloumns) {
		// TODO Auto-generated method stub
		new CommonDataBase(context, tableName, coloumns) {

			@Override
			public ContentValues getContentValues(JSONObject jsonObject)
					throws JSONException {
				// TODO Auto-generated method stub
				return getContentValues(jsonObject);
			}
		};
	}

	public long addItem(JSONObject jsonObject) throws JSONException {
		return mInsertOrQuery.addItem(jsonObject);
	}

	public Cursor getItem() {
		return mInsertOrQuery.getItem();
	}

	protected abstract ContentValues getContentValues(JSONObject jsonObject)
			throws JSONException;
}
